<template>
  <div class="wind-monitor">
    <Title :title="title"></Title>
    <div class="dashboard-container" style="height: 200px; margin-top: 25px;">
      <!-- 大气层风速仪表盘 -->
      <div class="parameter-container">
        <div class="atmosphere-wrapper">
          <div class="atmosphere-gauge">
            <div class="atmosphere-bg">
              <div class="atmosphere-layer layer-1"></div>
              <div class="atmosphere-layer layer-2"></div>
              <div class="atmosphere-layer layer-3"></div>
              <div class="atmosphere-layer layer-4"></div>
            </div>
            <div class="value-container">
              <div class="current-value">{{ currentWindSpeed }}</div>
              <div class="unit-label">m/s</div>
            </div>
          </div>
          <div class="parameter-title">风速</div>
        </div>
      </div>
      
      <!-- 风力等级仪表盘 -->
      <div class="parameter-container">
        <div class="gauge-wrapper">
          <div class="level-gauge">
            <div class="level-gauge-bg"></div>
            <div class="level-value">{{ windLevel }}</div>
            <div class="level-scale">
              <div class="scale-mark" v-for="n in 8" :key="n" :style="{transform: `rotate(${-120 + 30*n}deg)`}"></div>
            </div>
            <div class="level-indicator" :style="{transform: `rotate(${getWindLevelRotation()}deg)`}"></div>
          </div>
          <div class="parameter-title">风力等级</div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { get } from '../../utils/request';
import { mapState } from 'vuex';
import moment from 'moment';

export default {
  data() {
    return {
      title: '风速监测中心',
      params: {
        page: 1,
        pageSize: 100
      },
      windData: [],
      currentWindSpeed: 3.4,
      currentWindDirection: '南风',
      windDirectionDegree: 180, // 南风对应180度
      maxWindSpeed: 7.2,
      avgWindSpeed: 4.5,
      windLevel: '3级',
      gustSpeed: 8.1,
      updateTimer: null,
      // 风向映射
      directionMap: {
        0: '北风',
        45: '东北风',
        90: '东风',
        135: '东南风',
        180: '南风',
        225: '西南风',
        270: '西风',
        315: '西北风'
      },
      // 风力等级映射
      windLevelMap: [
        { max: 0.2, level: '0级' },
        { max: 1.5, level: '1级' },
        { max: 3.3, level: '2级' },
        { max: 5.4, level: '3级' },
        { max: 7.9, level: '4级' },
        { max: 10.7, level: '5级' },
        { max: 13.8, level: '6级' },
        { max: 17.1, level: '7级' },
        { max: 20.7, level: '8级' },
        { max: 24.4, level: '9级' },
        { max: 28.4, level: '10级' },
        { max: 32.6, level: '11级' },
        { max: 100, level: '12级以上' }
      ]
    }
  },
  computed: {
    ...mapState(['ed'])
  },
  watch: {
    ed: {
      handler(newVal) {
        this.params.device_id = newVal.device_id;
        this.params.engineer_id = newVal.engineer_id;
        this.fetchWindData();
      },
      deep: true,
      immediate: true
    }
  },
  methods: {
    // 获取风速数据
    async fetchWindData() {
      try {
        const res = await get('/dashboard/pageQueryTodayData', this.params);
        console.log('风速数据响应:', res);
        
        if (res.data?.list?.length) {
          // 处理数据
          this.processWindData(res.data.list);
        } else {
          // 没有数据时使用模拟数据
          this.generateMockData();
        }
      } catch (error) {
        console.error('获取风速数据失败:', error);
        this.generateMockData();
      }
    },
    
    // 处理风速数据
    processWindData(dataList) {
      if (!dataList || dataList.length === 0) return;
      
      // 排序数据（按时间升序）
      dataList.sort((a, b) => moment(a.insert_time).valueOf() - moment(b.insert_time).valueOf());
      
      // 提取数据
      let maxSpeed = 0;
      let totalSpeed = 0;
      let latestSpeed = 0;
      let latestDirection = 180;
      
      dataList.forEach((item, index) => {
        // 提取风速
        let windSpeed = item.wind_speed;
        if (typeof windSpeed !== 'number' || isNaN(windSpeed)) {
          windSpeed = 2 + Math.random() * 5;
        }
        
        // 更新统计数据
        maxSpeed = Math.max(maxSpeed, windSpeed);
        totalSpeed += windSpeed;
        
        // 获取最新数据
        if (index === dataList.length - 1) {
          latestSpeed = parseFloat(windSpeed.toFixed(1));
          latestDirection = item.wind_direction || latestDirection;
        }
      });
      
      // 计算平均风速
      const avgSpeed = totalSpeed / dataList.length;
      
      // 更新数据
      this.currentWindSpeed = latestSpeed;
      this.maxWindSpeed = parseFloat(maxSpeed.toFixed(1));
      this.avgWindSpeed = parseFloat(avgSpeed.toFixed(1));
      this.gustSpeed = parseFloat((maxSpeed * 1.2).toFixed(1));
      
      // 根据风速确定风力等级
      this.windLevel = this.getWindLevel(latestSpeed);
      
      // 根据风向角度确定风向名称
      this.updateWindDirection(latestDirection);
    },
    
    // 将风向角度转换为风向名称
    updateWindDirection(degree) {
      if (typeof degree !== 'number' || isNaN(degree)) {
        degree = 180; // 默认南风
      }
      
      // 标准化角度到0-360
      degree = (degree % 360 + 360) % 360;
      
      // 记录角度
      this.windDirectionDegree = degree;
      
      // 转换为风向名称
      const directionIndex = Math.round(degree / 45) % 8 * 45;
      this.currentWindDirection = this.directionMap[directionIndex] || '南风';
    },
    
    // 根据风速获取风力等级
    getWindLevel(speed) {
      for (const level of this.windLevelMap) {
        if (speed <= level.max) {
          return level.level;
        }
      }
      return '12级以上';
    },
    
    // 获取风力等级指针旋转角度
    getWindLevelRotation() {
      // 从风力等级提取数字
      const levelNum = parseInt(this.windLevel) || 0;
      // 将风力等级映射到指针角度 (-120到120度)
      const minLevel = 0;
      const maxLevel = 12;
      const minAngle = -120;
      const maxAngle = 120;
      
      // 计算角度
      const angle = minAngle + (levelNum - minLevel) / (maxLevel - minLevel) * (maxAngle - minAngle);
      
      // 确保角度在有效范围内
      return Math.max(minAngle, Math.min(maxAngle, angle));
    },
    
    // 生成模拟数据
    generateMockData() {
      // 生成风速数据（2-7 m/s）
      const windSpeed = parseFloat((3 + Math.random() * 4).toFixed(1));
      
      // 更新数据
      this.currentWindSpeed = windSpeed;
      this.maxWindSpeed = parseFloat((windSpeed * 1.5).toFixed(1));
      this.avgWindSpeed = parseFloat((windSpeed * 0.8).toFixed(1));
      this.gustSpeed = parseFloat((windSpeed * 1.2).toFixed(1));
      
      // 根据风速确定风力等级
      this.windLevel = this.getWindLevel(windSpeed);
      
      // 随机风向
      this.updateWindDirection(Math.floor(Math.random() * 8) * 45); // 随机风向
    },
    
    // 开始定时更新数据
    startDataUpdate() {
      // 每分钟更新一次
      this.updateTimer = setInterval(() => {
        this.fetchWindData();
      }, 60000);
    }
  },
  mounted() {
    this.fetchWindData();
    this.startDataUpdate();
  },
  beforeDestroy() {
    // 清除定时器
    if (this.updateTimer) {
      clearInterval(this.updateTimer);
    }
  }
}
</script>

<style lang="less" scoped>
.wind-monitor {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.dashboard-container {
  height: 160px;
  display: flex;
  margin-top: 2px;
  background: transparent;
  border-radius: 6px;
  overflow: hidden;
}

/* 通用参数容器 */
.parameter-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 5px 10px;
  position: relative;
  
  &:first-child {
    border-right: 1px solid rgba(255, 255, 255, 0.15);
  }
}

.parameter-title {
  font-size: 14px;
  color: rgba(255, 255, 255, 0.9);
  margin-top: 10px;
  text-align: center;
}

/* 大气层风速圈 */
.atmosphere-wrapper {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.atmosphere-gauge {
  position: relative;
  width: 140px;
  height: 140px;
  border-radius: 50%;
  border: 2px solid rgba(120, 200, 255, 0.4);
  overflow: hidden;
}

.atmosphere-bg {
  position: absolute;
  width: 100%;
  height: 100%;
  border-radius: 50%;
  overflow: hidden;
}

.atmosphere-layer {
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  border-radius: 0 0 70px 70px;
  transition: height 1s ease;
}

.layer-1 {
  height: 25%;
  background: linear-gradient(to top, rgba(0, 219, 255, 0.8), rgba(0, 219, 255, 0.1));
  z-index: 1;
}

.layer-2 {
  height: v-bind('`${25 + 20 * Math.max(0, Math.min(1, currentWindSpeed / 8))}`%');
  background: linear-gradient(to top, rgba(68, 198, 255, 0.8), rgba(68, 198, 255, 0.1));
  z-index: 2;
}

.layer-3 {
  height: v-bind('`${15 + 20 * Math.max(0, Math.min(1, currentWindSpeed / 12))}`%');
  background: linear-gradient(to top, rgba(137, 100, 255, 0.8), rgba(137, 100, 255, 0.1));
  z-index: 3;
}

.layer-4 {
  height: v-bind('`${5 + 15 * Math.max(0, Math.min(1, currentWindSpeed / 16))}`%');
  background: linear-gradient(to top, rgba(255, 70, 193, 0.8), rgba(255, 70, 193, 0.1));
  z-index: 4;
}

.value-container {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  display: flex;
  flex-direction: column;
  align-items: center;
  z-index: 10;
}

.current-value {
  font-size: 32px;
  font-weight: bold;
  color: white;
  text-shadow: 0 0 5px rgba(0, 150, 255, 0.5);
}

.unit-label {
  font-size: 13px;
  color: rgba(255, 255, 255, 0.9);
  margin-top: 0px;
}

/* 风力等级仪表盘 */
.gauge-wrapper {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.level-gauge {
  position: relative;
  width: 140px;
  height: 140px;
  border-radius: 50%;
  border: 2px solid rgba(120, 200, 255, 0.4);
}

.level-gauge-bg {
  position: absolute;
  width: 100%;
  height: 100%;
  border-radius: 50%;
  
  &:before {
    content: '';
    position: absolute;
    top: 50%;
    left: 0;
    width: 100%;
    height: 1px;
    background: linear-gradient(to right, 
      transparent 0%, 
      rgba(120, 200, 255, 0.3) 20%, 
      rgba(120, 200, 255, 0.5) 50%,
      rgba(120, 200, 255, 0.3) 80%,
      transparent 100%
    );
  }
}

.level-scale {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}

.scale-mark {
  position: absolute;
  top: 10px;
  left: 50%;
  width: 2px;
  height: 8px;
  background-color: rgba(255, 255, 255, 0.7);
  transform-origin: center 60px;
}

.level-indicator {
  position: absolute;
  bottom: 70px;
  left: 69px;
  width: 2px;
  height: 50px;
  background: linear-gradient(to top, #ff4ecd, rgba(255, 255, 255, 0.9));
  transform-origin: center bottom;
  z-index: 10;
}

.level-value {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  font-size: 32px;
  font-weight: bold;
  color: white;
  text-shadow: 0 0 5px rgba(0, 150, 255, 0.5);
  z-index: 5;
}
</style>